package org.example.slave.packet;

import lombok.SneakyThrows;
import org.example.slave.util.ByteUtil;

/**
 * @author dingrui
 * @since 2022/2/16
 * @description
 */
public class OkPacket extends PacketWithHeader {

    private byte fieldCount;
    private byte[] affectedRows;
    private byte[] insertId;
    private int serverStatus;
    private int warningCount;
    private String message;

    public OkPacket() {
    }

    public OkPacket(byte[] data) {
        this.fromBytes(data);
    }

    @Override
    @SneakyThrows
    public void fromBytes(byte[] data) {
        int index = 0;
        // 1. read field count
        this.fieldCount = data[0];
        index++;
        // 2. read affected rows
        this.affectedRows = ByteUtil.readBinaryCodedLengthBytes(data, index);
        index += this.affectedRows.length;
        // 3. read insert id
        this.insertId = ByteUtil.readBinaryCodedLengthBytes(data, index);
        index += this.insertId.length;
        // 4. read server status
        this.serverStatus = ByteUtil.readUnsignedShortLittleEndian(data, index);
        index += 2;
        // 5. read warning count
        this.warningCount = ByteUtil.readUnsignedShortLittleEndian(data, index);
        index += 2;
        // 6. read message.
        this.message = new String(ByteUtil.readFixedLengthBytes(data, index, data.length - index));
        // end read
    }
}
